﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ATW.MT.BUS;
using System.Data;
using ATW.MT.CommonClass;
using System.Text;
using System.IO;
using System.Configuration;

namespace ATW.MT.BaseManage
{
    public partial class CatalogManage : CommonPage
    {
        bus_T_InformationCategory Tic = new bus_T_InformationCategory();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserInfo"] == null)
            {
                Server.Transfer("../Main/Login.aspx");
                return;
            }
            if (!IsPostBack)
            {
                BindData();
            }
        }

        //数据绑定
        private void BindData()
        {
            try
            {
                string strName = txtDiName.Value.Trim();
                string strStatus = ddlStatus.SelectedValue;
                DataTable dt = Tic.CatePagerQuery(strName, strStatus, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize);
                if (dt != null && dt.Rows.Count > 0)
                {
                    AspNetPager1.RecordCount = Convert.ToInt32(dt.Rows[0]["totalpagesize"]);
                    string filePath = ConfigurationManager.AppSettings["GetFilePath"];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        dt.Rows[i]["ticPictureUrl"] = filePath + dt.Rows[i]["ticPictureUrl"].ToString();
                    }
                }
                else
                {
                    AspNetPager1.RecordCount = 0;
                }
                rpList.DataSource = dt;
                rpList.DataBind();
            }
            catch (Exception ex)
            {

            }

        }

        //查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            BindData();
        }

        protected void AspNetPager1_pageChanged(object sender, EventArgs e)
        {
            BindData();
        }


        //编辑界面 确认按钮事件
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                string strId = "";
                string strName = "";
                string strDesc = "";
                string strUrl = "";
                //根据主键是否为空，判断为新增或者修改
                if (string.IsNullOrWhiteSpace(txtId.Value))
                {
                    strName = txtName.Value.Trim();
                    strDesc = txtDesc.Value.Trim();
                    if (hdfImg.Value != "")
                    {
                        strUrl = hdfImg.Value;
                    }
                    if (strName == "")
                    {
                        Tips("类别名称不能为空！");
                        return;
                    }
                    if (strDesc == "")
                    {
                        Tips("类别描述不能为空！");
                        return;
                    }
                    int result = Tic.Add(strName, strDesc, strUrl, ddlClassC.SelectedValue, ddlClassD.SelectedValue);
                    if (result > 0)
                    {
                        Tips("新增成功");
                        Clear();
                        BindData();
                    }
                    else
                    {
                        Tips("新增失败");
                        return;
                    }
                }
                else
                {
                    strId = txtId.Value;
                    strName = txtName.Value.Trim();
                    strDesc = txtDesc.Value.Trim();
                    if (hdfImg.Value != "")
                    {
                        strUrl = Path.GetFileName(hdfImg.Value);
                    }
                    if (strName == "")
                    {
                        Tips("类别名称不能为空！");
                        return;
                    }
                    if (strDesc == "")
                    {
                        Tips("类别描述不能为空！");
                        return;
                    }
                    int result = Tic.Modify(strId, strName, strDesc, strUrl, ddlClassC.SelectedValue, ddlClassD.SelectedValue);
                    if (result > 0)
                    {
                        Tips("修改成功");
                        Clear();
                        BindData();
                    }
                    else
                    {
                        Tips("修改失败");
                        return;
                    }
                }


            }
            catch (Exception ex)
            {
                //return "操作失败:" + ex.Message;
            }
        }
        //删除
        protected void lbnDelete_Click(object sender, EventArgs e)
        {
            LinkButton lbn = (LinkButton)sender;
            string strId = lbn.CommandArgument;
            try
            {
                int result = Tic.UserChangeStatus(strId, "2");
                if (result > 0)
                {
                    Tips("删除成功");
                    BindData();
                }
                else
                {
                    Tips("删除失败");
                }
            }
            catch (Exception ex)
            {

            }
        }

        //修改
        protected void lbnModify_Click(object sender, EventArgs e)
        {
            LinkButton lbn = (LinkButton)sender;
            string strId = lbn.CommandArgument;
            try
            {
                DataTable dtResult = Tic.SelectItem(strId);
                initList(strId);
                if (dtResult.Rows.Count > 0)
                {
                    this.txtId.Value = dtResult.Rows[0]["TICID"].ToString();
                    this.txtName.Value = dtResult.Rows[0]["ticName"].ToString();
                    this.txtDesc.Value = dtResult.Rows[0]["ticDesc"].ToString();
                    this.imgPrev.Src = ConfigurationManager.AppSettings["GetFilePath"].ToString() + dtResult.Rows[0]["ticPictureUrl"].ToString();
                    if (dtResult.Rows[0]["ticPictureUrl"].ToString() != "")
                    {
                        hdfImg.Value = dtResult.Rows[0]["ticPictureUrl"].ToString();
                    }
                    if (dtResult.Rows[0]["level_c_supply"].ToString() != "")
                    {
                        ddlClassC.Items.FindByValue(dtResult.Rows[0]["level_c_supply"].ToString()).Selected = true;
                    }
                    if (dtResult.Rows[0]["level_d_supply"].ToString() != "")
                    {
                        ddlClassD.Items.FindByValue(dtResult.Rows[0]["level_d_supply"].ToString()).Selected = true;
                    }
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("<script language='javascript'>");
                sb.Append("var divAdd = new jSharp.popUpDiv('divAdd');function Show(){divAdd.Show()} Show(); $('#hideAdd').click(function () {divAdd.Close();})");
                sb.Append("</script>");
                ClientScript.RegisterStartupScript(this.GetType(), "LoadPicScript", sb.ToString());

            }
            catch (Exception ex)
            {

            }
        }
        //恢复
        protected void lbnRecover_Click(object sender, EventArgs e)
        {
            LinkButton lbn = (LinkButton)sender;
            string cid = lbn.CommandArgument;
            try
            {
                int result = Tic.UserChangeStatus(cid, "1");
                if (result > 0)
                {
                    Tips("恢复成功");
                    BindData();
                }
                else
                {
                    Tips("恢复失败");
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void initList(string ticid)
        {//初始化候选列表
            try
            {
                ddlClassC.Items.Clear();
                ddlClassD.Items.Clear();
                DataTable dt = Tic.GetAuthedUser(ticid);
                if (dt != null && dt.Rows.Count > 0)
                {
                    ddlClassC.Items.Add(new ListItem("无", ""));
                    ddlClassD.Items.Add(new ListItem("无", ""));
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ddlClassC.Items.Add(new ListItem(dt.Rows[i]["tauname"].ToString(), dt.Rows[i]["tauid"].ToString()));
                        ddlClassD.Items.Add(new ListItem(dt.Rows[i]["tauname"].ToString(), dt.Rows[i]["tauid"].ToString()));
                    }
                }
                else
                {
                    ddlClassC.Items.Add(new ListItem("无授权用户", ""));
                    ddlClassD.Items.Add(new ListItem("无授权用户", ""));
                }
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 上传文件（返回文件名）
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private string Upload(FileUpload file)
        {//上传
            if (file.HasFile)
            {
                string filename = file.FileName;
                string ext = Path.GetExtension(filename).ToLower();
                //允许文件的后缀
                String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".bmp" };
                //看包含的文件是否是被允许的文件的后缀
                bool allow = false;
                for (int c = 0; c < allowedExtensions.Length; c++)
                {
                    if (ext == allowedExtensions[c])
                    {
                        allow = true;
                    }
                }
                if (!allow)
                {
                    Tips("不正确的文件格式！");
                    return "";
                }
                string path = ConfigurationManager.AppSettings["UploadFilePath"].ToString();
                filename = DateTime.Now.ToString("yyyyMMddHHmmss") + filename;
                string fullPath = Server.MapPath(path);
                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }
                fullPath = fullPath + filename;
                file.SaveAs(fullPath);
                return filename;
            }
            return "";
        }
        private void writeRes(string s)
        {
            Response.Clear();
            Response.Write(s);
            Response.End();
        }

        //清空控件
        private void Clear()
        {
            txtId.Value = "";
            txtName.Value = "";
            txtDesc.Value = "";
        }
        private void Tips(string s)
        {
            StringBuilder strScript = new StringBuilder();
            strScript.Append(@"<script language=javascript>
                var divTips=new jSharp.popUpDiv('divMsg');
                document.getElementById('msgContent').innerHTML='" + s + @"';
                divTips.Show();
                var t=setTimeout(function(){
                    divTips.Close();
                    clearTimeout(t);
                },1000);
            </script>");
            this.ClientScript.RegisterStartupScript(this.GetType(), "tips", strScript.ToString());
        }
    }
}